package com.along.textdemo.view;


import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.along.textdemo.R;
import com.along.textdemo.manager.AudioManager;
import com.along.textdemo.manager.DialogManager;
import com.along.textdemo.manager.DialogVoiceManager;
import com.along.textdemo.utils.FileUtils;

public class VoiceRecorderButton extends TextView implements AudioManager.AudioStateListener {

    private static final int STATE_NORMAL = 1;//正常状态
    private static final int STATE_RECORDING = 2;//录音状态
    private static final int STATE_WANT_TO_CANCEL = 3;//取消状态
    private static final String TAG = "AudioRecorderButton";

    private int mCurState = STATE_NORMAL;//当前状态

    private boolean isRecording = false;//是否正在录音
    private DialogVoiceManager mDialogManger;
    private AudioManager mAudioManager;

    private boolean mReady = false;//是否触发longClick
    private float mTime;//计时

    private Context mContext;

    public VoiceRecorderButton(Context context) {
        this(context, null);
    }

    public VoiceRecorderButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VoiceRecorderButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        mDialogManger = new DialogVoiceManager(getContext());

        String dir = FileUtils.audioSavePath(mContext);
        mAudioManager = AudioManager.getmInstance(dir);
        mAudioManager.setAudioStateListener(this);

        setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                mReady = true;
                mAudioManager.prepareAudio();
                return false;
            }
        });
    }
    float startY = 0;
    float moveY = 0;
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                changeSate(STATE_RECORDING);
                startY = event.getY();
                break;

            case MotionEvent.ACTION_MOVE:
                if (isRecording) {//正在录音
                    Log.e("move","开始录音=");
                     moveY = event.getY();
                     int instance = (int)Math.abs(moveY - startY);
                    if ( instance> 200){//向上滑动距离大于200
                        changeSate(STATE_WANT_TO_CANCEL);
                        mDialogManger.upShowRedCancel();
                    }else{
                        changeSate(STATE_RECORDING);
                        mDialogManger.downShowGreyCancel();
                    }
                }
                break;

            case MotionEvent.ACTION_UP:
                if (!mReady) {
                    reset();
                    return super.onTouchEvent(event);
                }
                if (!isRecording || mTime < 0.6f) {
                    mDialogManger.tooShort();
                    mAudioManager.cancel();
                    mHandler.sendEmptyMessageDelayed(MSG_LODING_DISMISS, 1000);
                } else if (mCurState == STATE_RECORDING) {//正常录制结束

                    mDialogManger.dismissDialog();
                    mDialogManger.stopWave();
                    mAudioManager.release();
                    if (mListener != null) {
                        mListener.onFinish(mTime, mAudioManager.getmCurrentFilePath());
                    }
                    Toast.makeText(mContext,"发出语音"+mAudioManager.getmCurrentFilePath(),Toast.LENGTH_SHORT).show();
                } else if (mCurState == STATE_WANT_TO_CANCEL) {
                    mDialogManger.dismissDialog();
                    mAudioManager.cancel();
                }
                reset();
                break;
        }
        return super.onTouchEvent(event);
    }

    /**
     * 根据不同状态，更改不同的显示的背景
     */
    Drawable drawable;
    private void changeSate(int stateRecording) {
        if (mCurState != stateRecording) {
            mCurState = stateRecording;

            switch (mCurState) {
                case STATE_NORMAL:
                    setBackground(null);
                    // 使用代码设置drawableleft
                    drawable = getResources().getDrawable(R.drawable.voice_talk_white);
                    // 这一步必须要做，否则不会显示。
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),drawable.getMinimumHeight());
                    setCompoundDrawables(null, null,null,drawable);
                    setText("");
                    mDialogManger.stopWave();
                    break;

                case STATE_RECORDING:
                    setBackground(null);
                    drawable = getResources().getDrawable(R.drawable.voice_talk_blue);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),drawable.getMinimumHeight());
                    setCompoundDrawables(null, null,null,drawable);
                    setText("松开发送");
                    if (isRecording) {
                        mDialogManger.showWave();
                    }
                    break;

                case STATE_WANT_TO_CANCEL:
                    setBackground(null);
                    drawable = getResources().getDrawable(R.drawable.voice_talk_gray);
                    // 这一步必须要做，否则不会显示。
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),drawable.getMinimumHeight());
                    setCompoundDrawables(null, null,null,drawable);
                    setText("");
                    break;
            }
        }
    }


    /**
     * 重置标识位
     */
    private void reset() {
        changeSate(STATE_NORMAL);
        isRecording = false;
        mReady = false;
        mTime = 0;
    }

    /**
     * 开始播放时回调此方法
     */
    @Override
    public void wellPrepared() {
        mHandler.sendEmptyMessage(MSG_AUDIO_PREPARED);
    }

    private static final int MSG_AUDIO_PREPARED = 0x110;
    private static final int MSG_LODING_DISMISS = 0x112;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_AUDIO_PREPARED:
                    mDialogManger.showRecordeingDialog();
                    mDialogManger.showWave();
                    isRecording = true;
                    new Thread(mGetVoiceLevelRunnable).start();
                    break;
                case MSG_LODING_DISMISS:
                    mDialogManger.dismissDialog();
                    break;
            }
        }
    };

    /**
     * 获取音量大小，并计时
     */
    private Runnable mGetVoiceLevelRunnable = new Runnable() {
        @Override
        public void run() {
            while (isRecording) {
                SystemClock.sleep(100);
                mTime += 0.1f;
            }
        }
    };

    /**
     * 完成录制后的回调接口
     */
    public interface AudioFinishRecorderListener {
        void onFinish(float time, String filePath);
    }

    private AudioFinishRecorderListener mListener;

    public void setAudioFinishRecorderListener(AudioFinishRecorderListener listener) {
        mListener = listener;
    }
}
